﻿using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace ASPNETVN.PORTAL.Modules.DOCUMENT.Components
{
    public partial class Spider
    {
        private static void CopyData(Stream FromStream, Stream ToStream)
        {
            const int intSize = 4096;
            Byte[] buffer = new Byte[intSize];
            int intBytesRead = FromStream.Read(buffer, 0, intSize);
            while (intBytesRead > 0)
            {
                ToStream.Write(buffer, 0, intBytesRead);
                intBytesRead = FromStream.Read(buffer, 0, intSize);
            }
        }

        public static void DownloadAttachment(string url)
        {
            MemoryStream ms = null;
            FileStream fs = null;

            try
            {
                string filename = url.Substring(url.LastIndexOf('/'));
                WebRequest req = WebRequest.Create(url);
                req.Method = "GET";
                WebResponse rsp = null;

                try
                {
                    rsp = req.GetResponse();
                    ms = new MemoryStream();
                    CopyData(rsp.GetResponseStream(), ms);
                    fs = new FileStream("C:\\Downloads\\" + filename, FileMode.Create);
                    fs.Write(ms.ToArray(), 0, (int)ms.Length);
                }
                catch
                {
                }
                finally
                {
                    if (ms != null) ms.Close();
                    if (rsp != null) rsp.GetResponseStream().Close();
                    if (fs != null) fs.Close();
                }
            }
            catch
            {
            }
        }

        private static Microsoft.Web.Testing.Light.HtmlElement GetRootElement(string url)
        {
            // Create a request for the URL.         
            WebRequest request = WebRequest.Create(url);

            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Remove the DOCTYPE.
            responseFromServer = Regex.Replace(responseFromServer, @"\<\!DOCTYPE.*?\>", string.Empty);


            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();

            // Load the response into an HtmlElement.
            return Microsoft.Web.Testing.Light.HtmlElement.Create(responseFromServer);

        }
    }
}
